package cvi.com.reader.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import android.support.design.widget.TabLayout;
import com.heima.tabview.library.TabViewChild;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import butterknife.BindView;
import cvi.com.reader.R;
import cvi.com.reader.adapter.PoetryCollectAdapter;
import cvi.com.reader.base.BaseActivity;
import cvi.com.reader.bean.CategoriesBean;
import cvi.com.reader.bean.FirstClassTextBookBean;
import cvi.com.reader.bean.HotBean;
import cvi.com.reader.bean.SecondClassTextBookBean;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.UtilsOnclickListen;
import cvi.com.reader.tool.refresh.CustomRefreshFooter;
import cvi.com.reader.tool.refresh.CustomRefreshHeader;
import cvi.com.reader.widgets.MultiStateView;
import cvi.com.reader.widgets.MyGridView;
import io.reactivex.schedulers.Schedulers;

public class PoetryCollectionAcitivity extends BaseActivity implements View.OnClickListener, PoetryCollectAdapter.CollectListener{
    @BindView(R.id.fragment_name)
    TextView fragmentName;
    @BindView(R.id.user_info)
    LinearLayout userInfo;
    @BindView(R.id.gridview)
    MyGridView gridview;
    @BindView(R.id.first_tabLayout)
    TabLayout firstTabLayout;
    @BindView(R.id.second_tabLayout)
    TabLayout secondTabLayout;
    @BindView(R.id.bb)
    View bb;
    @BindView(R.id.stateView)
    MultiStateView stateView;
    @BindView(R.id.smartRefreshLayout_home)
    SmartRefreshLayout smartRefreshLayout;
    //诗词大会，首页，课本，绘本，文学巨匠
    private List<CategoriesBean.RowsBean> rowsBeanList = new ArrayList<CategoriesBean.RowsBean>();
    private List<FirstClassTextBookBean.RowsBean> firtList = new ArrayList<FirstClassTextBookBean.RowsBean>();
    private List<SecondClassTextBookBean.RowsBean> secondList = new ArrayList<SecondClassTextBookBean.RowsBean>();
    private int has_children = -1;
    private int pid = -1;
    private List<TabViewChild> tabViewChildList = new ArrayList<>();
    private int first_id = -1;
    private int second_id = -1;
    private int first_chilren = -1;
    private List<HotBean.RowsBean> bookBeanList = new ArrayList<>();
    private PoetryCollectAdapter poetryCollectAdapter = null;
    private String  name;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_poetry_collection;
    }

    @Override
    protected void initView() {
        initSmartRefreshLayout();
        stateView.getBackground().setAlpha(153);
        userInfo.setOnClickListener(this);
        fragmentName.setText("诗词大汇");
        if (Hawk.contains("categoriesBeanList")) {
            rowsBeanList = Hawk.get("categoriesBeanList");
        }
        if (rowsBeanList != null) {
            for (int i = 0; i < rowsBeanList.size(); i++) {
                if ("诗词大汇".equals(rowsBeanList.get(i).getName())) {
                    pid = rowsBeanList.get(i).getId();
                    has_children = rowsBeanList.get(i).getHas_children();

                }
            }
        }
    }

    @Override
    protected void initData() {
        //绑定生命周期,获取宫格数据
        NetWorkManager.getInstance().getNetWorkApiService().getLTextBookData(pid).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PoetryCollectionAcitivity.this) {

                    @Override
                    protected void onSuccess(JSONObject response) {
                        //拿到所有的宫格数据及热门接口id;宫格界面数据目前写死，不使用此接口数据展示仅用接口数据各宫格id进入二级界面。
                        getData(response);
                        //  stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                    }
                });
    }
    //初始化下拉刷新控件
    private void initSmartRefreshLayout() {
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setRefreshHeader(new CustomRefreshHeader(PoetryCollectionAcitivity.this));
        smartRefreshLayout.setRefreshFooter(new CustomRefreshFooter(PoetryCollectionAcitivity.this, "加载中…"));
        smartRefreshLayout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        smartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //  presenter.onLoadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                bookBeanList.clear();
                getWorkList(first_id);
            }
        });

    }

    private void getData(JSONObject response) {
        firstTabLayout.removeAllTabs();
        JSONArray array = response.getJSONArray("rows");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            FirstClassTextBookBean.RowsBean rowsBean = (FirstClassTextBookBean.RowsBean) JSONObject.toJavaObject(object, FirstClassTextBookBean.RowsBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            firtList.add(rowsBean);
        }

        for (int i = 0; i < firtList.size(); i++) {
            TabLayout.Tab tab = firstTabLayout.newTab();
            tab.setText(firtList.get(i).getName());
            if (firtList.get(i).getName().equals(name)) {
                //初始化界面
                first_id = firtList.get(i).getId();
                first_chilren = firtList.get(i).getHas_children();
                firstTabLayout.addTab(tab, true);
                if (1 == first_chilren) {
                    getCategories(first_id);
                    secondTabLayout.setVisibility(View.VISIBLE);
                    bb.setVisibility(View.VISIBLE);
                } else {
                    getWorkList(first_id);
                    secondTabLayout.setVisibility(View.GONE);
                    bb.setVisibility(View.GONE);
                }
            } else {
                firstTabLayout.addTab(tab, false);
            }
            Log.d("start_first_id", first_id + "");
        }

        firstTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                for (int i = 0; i < firtList.size(); i++) {

                    if (tab.getText().toString().trim().equals(firtList.get(i).getName())) {
                        first_id = firtList.get(i).getId();
                        first_chilren = firtList.get(i).getHas_children();
                        if (1 == first_chilren) {
                            getCategories(first_id);
                            Log.d("second_id_first_id111", first_id + "");
                        } else {
                            stateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
                            getWorkList(first_id);
                            Log.d("second_id_first_id222", first_id + "");
                        }


                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void getCategories(int first_Id) {
        //绑定生命周期,获取宫格数据
        NetWorkManager.getInstance().getNetWorkApiService().getLTextBookData(first_Id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PoetryCollectionAcitivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        //拿到所有的宫格数据及热门接口id;宫格界面数据目前写死，不使用此接口数据展示仅用接口数据各宫格id进入二级界面。
                        getSecondData(response);
                    }
                });
    }

    private void getSecondData(JSONObject response) {
        secondList.clear();
        secondTabLayout.removeAllTabs();
        JSONArray array = response.getJSONArray("rows");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            SecondClassTextBookBean.RowsBean rowsBean = (SecondClassTextBookBean.RowsBean) JSONObject.toJavaObject(object, SecondClassTextBookBean.RowsBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            secondList.add(rowsBean);
        }
        Log.d("sddsvfgsf", secondList.size() + "");
        if (secondList.size() == 0) {
            secondTabLayout.setVisibility(View.GONE);
        }
        for (int i = 0; i < secondList.size(); i++) {
            if (secondList.size() == 0) {
                return;
            }
            TabLayout.Tab tab = secondTabLayout.newTab();
            tab.setText(secondList.get(i).getName());
            if (i == 0) {
                second_id = secondList.get(i).getId();
                //初始化界面
                getWorkList(second_id);
                secondTabLayout.addTab(tab, true);
            } else {
                secondTabLayout.addTab(tab, false);
            }
            Log.d("start_second_id", second_id + "");
        }
        secondTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                for (int i = 0; i < secondList.size(); i++) {
                    if (tab.getText().toString().trim().equals(secondList.get(i).getName())) {
                        second_id = secondList.get(i).getId();
                        getWorkList(second_id);
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void getWorkList(int id) {
        Log.d("second_id", second_id + "");
        //绑定生命周期,获取宫格数据
        NetWorkManager.getInstance().getNetWorkApiService().getLTextBookListData(id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PoetryCollectionAcitivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        //展示课本列表数据
                        setWorkData(response);
                        stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        smartRefreshLayout.finishRefresh(true);
                    }
                });

    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_info:
                if (UtilsOnclickListen.isFastClick()) {
                    jump(PersonalActivity.class);
                }
                break;
        }
    }

    private void setWorkData(JSONObject response) {
        bookBeanList.clear();
        JSONArray array = response.getJSONArray("rows");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            HotBean.RowsBean rowsBean = (HotBean.RowsBean) JSONObject.toJavaObject(object, HotBean.RowsBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            bookBeanList.add(rowsBean);
        }
        poetryCollectAdapter = new PoetryCollectAdapter(PoetryCollectionAcitivity.this, bookBeanList);
        poetryCollectAdapter.setCollectListener(this);
        gridview.setAdapter(poetryCollectAdapter);
        poetryCollectAdapter.notifyDataSetChanged();
    }

    @Override
    public void onCollectClick(String flag, int id) {
        if ("1".equals(flag)) {
            //绑定生命周期,获取宫格数据
            NetWorkManager.getInstance().getNetWorkApiService().setCollect(id).compose(this.<JSONObject>bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new DefaultObserver<JSONObject>(PoetryCollectionAcitivity.this) {
                        @Override
                        protected void onSuccess(JSONObject response) {
                            //收藏之后，重新请求数据，清空元数据
                            bookBeanList.clear();
                            if (0 == first_chilren) {
                                getWorkList(first_id);
                            } else {
                                getWorkList(second_id);
                            }


                        }
                    });

        } else {
            //绑定生命周期,获取宫格数据
            NetWorkManager.getInstance().getNetWorkApiService().removeCollect(id).compose(this.<JSONObject>bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new DefaultObserver<JSONObject>(PoetryCollectionAcitivity.this) {
                        @Override
                        protected void onSuccess(JSONObject response) {
                            //收藏之后，重新请求数据，清空元数据
                            bookBeanList.clear();
                            if (0 == first_chilren) {
                                getWorkList(first_id);
                            } else {
                                getWorkList(second_id);
                            }

                        }
                    });
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    protected void extrasDoSome(Bundle extras) {
        name=   (String) extras.get("getName");

    }
}
